<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/27
 * Time: 10:16
 */

namespace zhtfrontend\modules\sitepadapi\controllers;

use zhtfrontend\models\datas\Headmaster;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CommentInfo;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use yii\helpers\Json;
use yii\web\Response;

class CommentteacherController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\Teacher';
    public $adminModel='zhtfrontend\models\datas\Admin';
    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];

        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    //点评老师（班主任点评老师，老师点评老师，管家点评老师）列表获取
    public function actionList($admin_id){
        //首先根据admin_id查出来是什么角色
        $role=Admin::findOne($admin_id);
        $return=[];
        //如果角色是manager,那么就搜索出所有的教师
        if ($role['role']=='manager'){
            $teacher_list = Teacher::find()->all();
            if (!empty($teacher_list)){
                foreach ($teacher_list as $val){
                    $teacher_arr=[];
                    $teacher_arr['id']=$val->id;
                    $teacher_arr['name']=$val->name;
                    $teacher_arr['mobile']=$val->mobile;
                    $teacher_arr['img']=$val->img;
                    $teacher_arr['created_at']=\Yii::$app->formatter->asDatetime($val->created_at);
                    $return[] = $teacher_arr;
                }
            }
        //如果角色是班主任，那么就搜索班主任下面的所有老师
        }else if ($role['role']=='class_teacher'){
            if (!empty($role['teacher_id'])){
                $teacher_list=Teacher::find()->where(['parent_id'=>$role['teacher_id']])->all();
                if (!empty($teacher_list)){
                    foreach ($teacher_list as $val){
                        $teacher_arr=[];
                        $teacher_arr['id']=$val->id;
                        $teacher_arr['name']=$val->name;
                        $teacher_arr['mobile']=$val->mobile;
                        $teacher_arr['img']=$val->img;
                        $teacher_arr['created_at']=\Yii::$app->formatter->asDatetime($val->created_at);
                        $return[] = $teacher_arr;
                    }
                }
            }
         //如果角色是教师的话，那么就找到它对应的他的班主任（一个）
        }else{
            if (!empty($role['teacher_id'])){
                $teacher_item=Teacher::findOne($role['teacher_id']);
                if(!empty($teacher_item)){
                    $teacher_list=Headmaster::find()->where(['id'=>$teacher_item->parent_id])->all();
                    if (!empty($teacher_list)){
                        foreach ($teacher_list as $val){
                            $teacher_arr=[];
                            $teacher_arr['id']=$val->id;
                            $teacher_arr['name']=$val->name;
                            $teacher_arr['mobile']=$val->mobile;
                            $teacher_arr['img']=$val->img;
                            $teacher_arr['created_at']=\Yii::$app->formatter->asDatetime($val->created_at);
                            $return[] = $teacher_arr;
                        }
                    }
                }
            }
        }
        return new ArrayDataProvider([
            'allModels' => $return,
            'pagination' => [
                'pageSize' => 10
            ],
        ]);
    }
    //下面是获取出来应该评价那些项目
    public function actionItems_bak(){
        $return=[];
        $comment_items=CommentInfo::find()->all();
        foreach ($comment_items as $key=>$val){
            $comment_type=explode(",",$val->comment_term_type);
            if (in_array("teacher", $comment_type)){
                $comment_items_arr=[];
                $comment_items_arr['id']=$val->id;
                $comment_items_arr['title']=$val->title;
                $comment_items_arr['score_levels']=[];
                $comment_items_arr['scores']='';
                $return[] = $comment_items_arr;
            }
        }
        return new ArrayDataProvider([
            'allModels' => $return,
        ]);
    }
    /*
     * 获取应该评价哪些项目以及已经评价的分数,valuator_id 评价者id,accepter_id被评价者id
     * 多加两个个参数实现通用看看行不行吧
     */
    public function actionItems($valuator_id,$accepter_id,$comment_type='comment_teacher'){//$accepter_id到底应该写成teacher_id还是admin_id，先按照admin_id来写吧
        if(empty($valuator_id) || empty($accepter_id)){
            return ['statusCode'=>200,'message' => 'error','result'=>'评价与被评价id不能为空'];
        }
        //根据评价者的id到admin表中查找它所属的角色
        $admin = (new Query())->select('*')->from('{{%admin}}')->where(['id'=>$valuator_id])->one(Fun::getSiteDb());
        $role = $admin['role'];
        $comment_info_arr1 = [];
        switch ($comment_type){
            case 'comment_teacher':
                $current_commenttype = 'teacher';
                $accepter_type = 3;
                break;
            case 'comment_headteacher'://评论班主任
                $current_commenttype = 'headteacher';
                $accepter_type = 4;
                break;
            case 'comment_manager'://评论管理员
                $current_commenttype = 'manager';
                $accepter_type = 1;
                break;

            default://评论管理员
                $current_commenttype = 'teacher';
                $accepter_type = 3;
                break;
        }
        switch ($role){//其实这个角色没大有必要，反正都是以admin表为基础的，万一以后有什么其他表也能加入进来，还是把角色整上吧，这样就能根据角色区分表了
            case 'teache_teacher'://角色为教师
                $valuator_type = 3;
                break;
            case 'class_teacher'://角色为班主任
                $valuator_type = 4;
                break;
            case 'manager'://角色为管理员
                $valuator_type = 1;
                break;
            default:
                $valuator_type = 3;
                break;
        }
        $comment_items = (new Query())->select('*')->from('{{%comment_info}}')->all(Fun::getSiteDb());
        foreach ($comment_items as $key=>$val) {
            $comment_type=explode(",",$val['comment_term_type']);
            if (in_array($current_commenttype, $comment_type)){
                $comment_info_arr1[] = [
                    'comment_info_id' => $val['id'],
                    'title' => $val['title'],
                    'comment_info_title' => '该员工的' . $val['title']
                ];
            }
        }
        if(!empty($comment_info_arr1)){
            $comment = (new Query())->select('*')->from('{{%comment}}')->where(['valuator_id'=>$valuator_id,'accepter_id'=>$accepter_id,'valuator_type'=>$valuator_type,'accepter_type'=>$accepter_type])->one(Fun::getSiteDb());
            $comment_info_arr = [];
            if(!empty($comment)){
                foreach ($comment_info_arr1 as $k=>$ci){
                    $commentRelation = (new Query())->select('*')->from('{{%comment_relation}}')->where(['comment_id'=>$comment['id'],'comment_info_id'=>$ci['comment_info_id']])->one(Fun::getSiteDb());
                    if(!empty($commentRelation)){
                        $ci['for_value'] = $commentRelation['for_value'];
                        $comment_info_arr[$k] = $ci;
                    }else{
                        $ci['for_value'] = 4;
                        $comment_info_arr[$k] = $ci;
                    }
                }
            }else{//如果
                foreach ($comment_info_arr1 as $k=>$ci){
                    $ci['for_value'] = 4;
                    $comment_info_arr[$k] = $ci;
                }
            }
            $data = [
                'accepter_id' => $accepter_id,
//            'teacher_name' => $accepter_headteacher['name'],
//            'title' => '针对' . $accepter_headteacher['name'] . '班主任,您的评价是:',
                'comment_info' => $comment_info_arr,
            ];
            return ['statusCode'=>200,'message' => 'success','items'=>$data];
        }else{
            $data = [
                'accepter_id' => $accepter_id,
                'comment_info' => null,
            ];
            return ['statusCode'=>200,'message' => 'success','items'=>$data];
        }

    }

    //班主任点评教师
    public function actionFindbyheadmaster($teacher_id)
    {
        $data = $comment_info_arr = [];
        $teachIds = (new Query())->select('teacher_id')->from('{{%arrange_course}} a')->leftJoin('{{%class_manage}} b', 'a.id=b.code')->where([
            'b.headmaster' => $teacher_id, 'a.site_id' => Fun::getSiteId()
        ])->column(Fun::getSiteDb());
        $teacher = (new Query())->select('*')->from('{{%admin}}')->where(['in', 'teacher_id', $teachIds])->andWhere(['role' => 'teache_teacher'])->all(Fun::getSiteDb());
        $commentInfo = CommentInfo::find()->where(['object_type' => 1])->asArray()->all();
        foreach ($commentInfo as $kk => $vv) {
            $comment_info_arr[] = [
                'comment_info_id' => $vv['id'],
                'comment_info_title' => '该教师的' . $vv['title']
            ];
        }
        foreach ($teacher as $kk => $vv) {
            $data[] = [
                'teacher_id' => $vv['id'],
                'title' => '针对' . $vv['name'] . '老师' . ',您的评价是:',
                'content' => $comment_info_arr
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20
            ],
            'sort' => [
                'attributes' => ['teacher_id']
            ]
        ]);
    }

    /*教师评价班主任 $valuator_id评价者id，$accepter_id被评价者id*/
    public function actionCommentonheadteacher($valuator_id,$accepter_id,$accepter_type){
        $post_data = \Yii::$app->request->post();
        $this->getSiteDb(Fun::getSiteId());
        $admin = (new Query())->select('*')->from('{{%admin}}')->where(['id'=>$valuator_id])->one();
        $adminrole = $admin['role'];
        $commentArr = $commentRelationArr = [];
        switch($accepter_type){
            case 1:
                $role = '管理员';break;
            case 2:
                $role = '学生';break;
            case 3:
                $role = '老师';break;
            case 4:
                $role = '工作人员';break;
            default:
                $role = '';break;
        }
        switch ($adminrole){//其实这个角色没大有必要，反正都是以admin表为基础的，万一以后有什么其他表也能加入进来，还是把角色整上吧，这样就能根据角色区分表了
            case 'teache_teacher'://角色为教师
                $valuator_type = 3;
                break;
            case 'class_teacher'://角色为班主任
                $valuator_type = 4;
                break;
            case 'manager'://角色为管理员
                $valuator_type = 1;
                break;
            default:
                $valuator_type = 3;
                break;
        }
        foreach($post_data['commentScores'] as $dk=>$dv){
            $commentArr[] = [
                'title' => '针对' . $dv['teacher_name'] . $role,
                'description' => $dv['content'],
                'accepter_id' => $accepter_id,//被评价的班主任对应teacher表的id
                'accepter_type' => $accepter_type,
                'valuator_id' => $valuator_id,//进行评价的老师对应的admin编号
                'valuator_type' => $valuator_type,

            ];
            $have_comment = (new Query())->select('*')->from('{{%comment}}')->where(['valuator_id'=>$valuator_id,'valuator_type'=>$valuator_type,'accepter_type'=>$accepter_type,'accepter_id'=>$accepter_id])->one();
            if(empty($have_comment)){
                \Yii::$app->db->createCommand()->insert('{{%comment}}', [
                    'title' => '针对' . $dv['teacher_name'] . $role,
                    'description' => $dv['content'],
                    'accepter_id' => $accepter_id,//被评价的班主任对应teacher表的id
                    'accepter_type' => $accepter_type,
                    'valuator_id' => $valuator_id,//进行评价的老师对应的admin编号
                    'valuator_type' => $valuator_type,
                ])->execute();
                $insertId = \Yii::$app->db->getLastInsertID();
                $comment_relation_info = $dv['comment_info'];
                if(!empty($comment_relation_info)){
                    foreach($comment_relation_info as $cri){
                        $commentRelationArr[] = [
                            'comment_id' => $insertId,
                            'comment_info_id' => $cri['comment_info_id'],
                            'for_value' => $cri['for_value']
                        ];
                    }
                }
            }else{
                $comment_relation_info = $dv['comment_info'];
                if(!empty($comment_relation_info)){
                    foreach($comment_relation_info as $cri){
                        $have_comment_relation = (new Query())->select('*')->from('{{%comment_relation}}')->where(['comment_id'=>$have_comment['id'],'comment_info_id'=>$cri['comment_info_id']])->one();
                        if(!empty($have_comment_relation)){
                            \Yii::$app->db->createCommand()->update('{{%comment_relation}}', ['for_value' => $cri['for_value']], ['comment_id'=>$have_comment['id'],'comment_info_id'=>$cri['comment_info_id']])->execute();
                        }else{
                            $commentRelationArr[] = [
                                'comment_id' => $have_comment['id'],
                                'comment_info_id' => $cri['comment_info_id'],
                                'for_value' => $cri['for_value']
                            ];
                        }
                    }
                }
            }
        }
        \Yii::$app->db->createCommand()->batchInsert('{{%comment_relation}}', [
            'comment_id', 'comment_info_id', 'for_value'
        ], $commentRelationArr)->execute();
        return ['statusCode' => 200, 'message' => 'success', 'items' => $commentRelationArr];
    }

    public function actionCreate()
    {
        $commentRelationArr = $commentInfoArr = $commentArr = $commentContent = [];
        $data = \Yii::$app->request->post();
        foreach (Json::decode($data['array']) as $dk => $dv) {
            $commentContent[$dv['teacher_id']] = $dv['content'];
            $commentInfoArr[$dv['teacher_id']] = $dv['value'][0];
        }
        foreach ($commentInfoArr as $k => $v) {
            $commentArr[] = [
                'object_type' => 1,
                'title' => $this->getAdmin($k),
                'description' => empty($commentContent[$k])?$this->getDescription($v['for_value']):$commentContent[$k],
                'object_id' => $k,
                'created_at'=>time(),
                'site_id'=>Fun::getSiteId()
            ];
        }
        $result = Fun::getSiteDb()->createCommand()->batchInsert('{{%comment}}', [
            'object_type', 'title', 'description', 'object_id'
        ], $commentArr)->execute();
        if ($result) {
            $comment = (new Query())->select('*')->from('{{%comment}}')->orderBy('id DESC')->limit($result)->all(Fun::getSiteDb());
            foreach ($comment as $key => $val) {
                $commentRelationArr[] = [
                    'comment_id' => $val['id'],
                    'comment_info_id' => $commentInfoArr[$val['object_id']]['comment_info_id'],
                    'for_value' => $commentInfoArr[$val['object_id']]['for_value']
                ];
            }
            Fun::getSiteDb()->createCommand()->batchInsert('{{%comment_relation}}', [
                'comment_id', 'comment_info_id', 'for_value'
            ], $commentRelationArr)->execute();
        }
        return $commentRelationArr;
    }
    

    private function getAdmin($teacher_id)
    {
        $teacher = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $teacher_id])->one(Fun::getSiteDb());
        $commentTitle = '针对' . $teacher['name'] . '老师' . ',您的评价是:';
        return $commentTitle;
    }

    protected function getDescription($data){
        $commentInfoData=(new Query())->select('*')->from('{{%comment_info}}')
            ->where(['object_type'=>1])->all(Fun::getSiteDb());
        $description='';
        if(isset($commentInfoData)){
            foreach($commentInfoData as $k=>$v){
                $description.='该老师的'.$v['title'].'评价是'.$data.'分;';
            }
            return $description;
        }
        return '';
    }
    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }
}